const router = require('koa-router')()
const fs = require('fs')

addMapping = (mapping) => {
    for(let url in mapping) {
        // console.log(url)
        if (url.startsWith('GET ')) {
            let path = url.substring(4)
            router.get(path, mapping[url])
        } else if (url.startsWith('POST ')) {
            let path = url.substring(5)
            router.post(path, mapping[url])
        } else {
            router.get('/404', ctx => {
                console.log(`invalid URL: ${url}`);
            })
        }
    }

}

addController = () => {
    var files = fs.readdirSync(__dirname + '/controllers')

    var js_files = files.filter((item) => {
        return item.endsWith('.js')
    })

    for(let f of js_files) {
        // console.log(`process controller: ${f}..`)
        let mapping = require(__dirname + '/controllers/' + f)
        return addMapping(mapping)

    }
}

module.exports =  () => {
    addController()
    return router.routes();
}